package com.jt.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @outhor fufeixiang
 * @date 2021-04-25
 */
//利用工厂动态为目标对象创建代理
public class JDKProxyFactory {

    public static Object getProxy(Object target){
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();

        //通过动态代理创建对象
        Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try{
                    //添加事务的控制
                    System.out.println("开启事务");
                    //执行目标方法
                    //target真实的目标对象，
                    result = method.invoke(target, args);

                    System.out.println("事务提交");
                }catch(Exception e){
                    e.printStackTrace();
                    System.out.println("事务回滚");
                }
                return result;
            }
        });
        return proxy;
    }

}
